import { FC, ReactNode, useEffect, useRef, useState } from "react";
import { Box, Flex, Text, Slider, HStack, SliderTrack, SliderFilledTrack, SliderThumb, Button, Icon, Tooltip, Popover, PopoverContent ,PopoverTrigger,PopoverBody,PopoverHeader, List, ListItem,Image} from "@chakra-ui/react";
import { FaPlay, FaPause, FaStepBackward, FaStepForward, FaHeart, FaDownload, FaComment, FaRedo, FaBars, FaUnlock, FaLock } from 'react-icons/fa';
import { RootState } from '@/store';
import { TriangleUpIcon } from '@chakra-ui/icons';
import styled from 'styled-components';import { formatTime } from "@/components/utils";
import { Song } from "@/faker/songs/ranking-songs";
import { setCurrentSong, setCurrentTime,setIsPlaying,setPlayMode } from "@/store/modules/player/reducer";
import { useAppDispatch, useAppSelector } from "@/hooks/store";
import { fetchRecommendArtists,fetchRecommendAlbums, fetchRecommendMvs } from "@/store/modules/recommend";
interface IProps {
    children?: ReactNode;
    song: Song;
    songs: Song[];
}
const AppPlayBar: FC<IProps> = ({ song,songs }) => {
    const dispatch = useAppDispatch();
    const [duration, setDuration] = useState(0); // 总时长
    const audioRef = useRef<HTMLAudioElement | null>(null);
    
    const [isLocked, setIsLocked] = useState(false); // 是否锁定
    const [isHovered, setIsHovered] = useState(false); // 鼠标是否悬停
    const [isMusicListOpen, setIsMusicListOpen] = useState(false); // 是否打开播放列表
    const {isPlaying,currentTime,playMode} = useAppSelector(state=>state.player)

    useEffect(()=>{
        dispatch(fetchRecommendAlbums())
        dispatch(fetchRecommendArtists())
        dispatch(fetchRecommendMvs())
    },[])
    useEffect(() => {
        if (audioRef.current) {
            audioRef.current.addEventListener('timeupdate', handleTimeUpdate);
            audioRef.current.addEventListener('ended', handleEnded);
            return () => {
                audioRef.current!.removeEventListener('timeupdate', handleTimeUpdate);
                audioRef.current!.removeEventListener('ended', handleEnded);
            };
        }
    }, []);

    // 监听鼠标移动事件
    useEffect(() => {
        const handleMouseMove = (event: MouseEvent) => {
            const windowHeight = window.innerHeight;
            const mouseY = event.clientY;

            // 判断鼠标是否在页面最底部附近（例如距离底部 50px 范围内）
            const isAtBottom = mouseY >= windowHeight - 50;

            // 如果鼠标在最底部且未锁定，则显示播放器和锁定按钮
            if (isAtBottom && !isLocked) {
                setIsHovered(true);
            } else if (!isLocked) {
                // 如果鼠标不在最底部且未锁定，则隐藏播放器和锁定按钮
                setIsHovered(false);
            }
        };

        // 添加 mousemove 事件监听器
        window.addEventListener('mousemove', handleMouseMove);

        // 清理事件监听器
        return () => {
            window.removeEventListener('mousemove', handleMouseMove);
        };
    }, [isLocked]);

    const handlePlayPause = () => {
        try {
            if (audioRef.current) {
                if (isPlaying) {
                    audioRef.current.pause();
                } else {
                    audioRef.current.play();
                }
                dispatch(setIsPlaying(!isPlaying));
            }
        } catch (error) {
            console.error('Error handling play/pause:', error);
        }
    };

    const handlePrev = () => {
        
        if(songs.length>0){
            const index = songs.findIndex(item=>item.id===song.id);
            if(index>0){
                dispatch(setCurrentSong(songs[index-1]));
            }else{
                dispatch(setCurrentSong(songs[songs.length-1]));
            }
        }
    };

    const handleTimeUpdate = () => {
        if (audioRef.current) {
            dispatch(setCurrentTime(audioRef.current.currentTime));
            setDuration(audioRef.current.duration);
        }
    };

    const toggleLock = () => {
        setIsLocked(!isLocked);
    };

    const handleEnded = () => {
        if (audioRef.current) {
            audioRef.current.pause();
        }
    };

    const handleNext = () => {
        if(songs.length>0){
            const index = songs.findIndex(item=>item.id===song.id);
            if(index<songs.length-1){
                dispatch(setCurrentSong(songs[index+1]));
            }else{
                dispatch(setCurrentSong(songs[0]));
            }
        }
    };

    return (
        <>
            {/* 锁定/解锁按钮 */}
            <LockButtonWrapper isHidden={!isHovered && !isLocked}>
                <Tooltip label={isLocked ? '解锁' : '锁定'} placement="top">
                    <Button onClick={toggleLock} variant="ghost">
                        {isLocked ? <Icon as={FaLock} /> : <Icon as={FaUnlock} />}
                    </Button>
                </Tooltip>
            </LockButtonWrapper>

            {/* 播放器主体 */}
            <StyledMusicPlayer isHidden={!isHovered && !isLocked} onMouseEnter={() => !isLocked && setIsHovered(true)} onMouseLeave={() => !isLocked && setIsHovered(false)}>
                <Box m={2}>
                    <Image src={song.picUrl} alt={song.name} width="50px" height="50px" />
                </Box>

                <Box flex="2" m={2} > 
                    <HStack>
                        <Text>{song.name}</Text>
                        <Text fontWeight="thin">{song.artist}</Text>
                        <Text fontSize="sm">{formatTime(currentTime)} / {formatTime(song.duration)}</Text>
                    </HStack>
                    <Slider
                        value={duration ? (currentTime / song.duration) * 100 : 0}
                        onChange={(value) => {
                            const newTime = (value / 100) * song.duration;
                            setCurrentTime(newTime);
                            if (audioRef.current) {
                                audioRef.current.currentTime = newTime;
                            }
                        }}
                        aria-label="Music playback progress"
                        colorScheme="blue"
                        min={0}
                        max={100}
                        height="8px" // 设置滑块的高度
                        width="100%" // 确保滑块占满父容器的宽度
                    >
                        <SliderTrack />
                        <SliderFilledTrack />
                        <SliderThumb boxSize={6} />
                    </Slider>
                </Box>

                <Box m="3">
                    <Button onClick={handlePrev} variant="ghost">
                        <Icon as={FaStepBackward} />
                    </Button>
                    <Button onClick={handlePlayPause} variant="ghost">
                        {isPlaying ? <Icon as={FaPause} /> : <Icon as={FaPlay} />}
                    </Button>
                    <Button onClick={handleNext} variant="ghost">
                        <Icon as={FaStepForward} />
                    </Button>
                </Box>

                <Box m="1">
                    <Button variant="ghost">
                        <Icon as={FaHeart} />
                    </Button>
                    <Button variant="ghost">
                        <Icon as={FaDownload} />
                    </Button>
                    <Button variant="ghost">
                        <Icon as={FaComment} />
                    </Button>
                    <Button variant="ghost">
                        <Icon as={FaRedo} />
                    </Button>
                    <Popover
                        isOpen={isMusicListOpen}
                        placement="top"
                        closeOnBlur={true}
                        onClose={()=>setIsMusicListOpen(false)}
                    >
                        <PopoverTrigger>
                            <Button variant="ghost" onClick={()=>setIsMusicListOpen(true)}>
                                <Icon as={FaBars}    />
                            </Button>
                        </PopoverTrigger>
                        <PopoverContent minW="620px" paddingInline={0}>
                            <PopoverHeader border="none"  h="60px" >
                                <Flex alignItems="center" lineHeight="60px"   >
                                    <Text fontWeight="bold"  >播放列表</Text>
                                    <Text fontSize="sm" color="gray.500">&nbsp;(共{songs.length}首)</Text>
                                </Flex>
                          
                            </PopoverHeader>
                            <PopoverBody maxH="300px" overflowY="auto" paddingInline={0}>
                                <List >
                                    {songs.map((item,index)=>(
                                        <ListItem key={index} 
                                            onClick={() => dispatch(setCurrentSong(item))}
                                            p={4}
                                            _hover={{bgColor:"gray.100"}}
                                            bgColor={item.id===song.id ? "gray.100" : ""}
                                        >
                                            <Flex>
                                                <Text flex="3">{}{item.id===song.id  ? <Icon as={TriangleUpIcon}/> : index+1}&nbsp;{item.name}</Text>
                                                <Text flex="1"  fontWeight="thin"  maxW="100px" overflow="hidden" textOverflow="ellipsis" whiteSpace="nowrap">{item.artist}</Text>
                                                <Text fontWeight="bold">{formatTime(item.duration)}</Text>
                                            </Flex>
    
                                        </ListItem>
                                    ))}
                                </List>
                            </PopoverBody>
                        </PopoverContent>
                    </Popover>

                </Box>

                <audio ref={audioRef} src={song.songUrl} />
            </StyledMusicPlayer>
        </>
    );
};

export default AppPlayBar;

// 样式定义
const StyledMusicPlayer = styled(Flex)<{ isHidden: boolean }>`
  align-items: center;
  padding: 4px;
  width: 100%;
  position: fixed;
  bottom: 0;
  z-index: 10;
  background: white;
  box-shadow: 20px 20px 80px rgb(211,211,211);
  opacity: ${(props) => (props.isHidden ? 0 : 1)};
  pointer-events: ${(props) => (props.isHidden ? 'none' : 'auto')};
  transition: opacity 0.3s ease-in-out;
`;

const LockButtonWrapper = styled(Box)<{ isHidden: boolean }>`
  position: fixed;
  bottom: ${(props) => (props.isHidden ? '0' : '30px')}; /* 与播放器的距离 */
  left: 50%;
  transform: translateX(-50%);
  z-index: 11;
  opacity: ${(props) => (props.isHidden ? 0 : 1)};
  pointer-events: ${(props) => (props.isHidden ? 'none' : 'auto')};
  transition: opacity 0.3s ease-in-out, bottom 0.3s ease-in-out;
`;